// 设备管理模块
const DeviceManager = {
    // 设备列表
    devices: [],
    
    // 初始化
    init() {
        this.initEventListeners();
        this.loadDevices();
        this.startDeviceMonitoring();
    },
    
    // 初始化事件监听器
    initEventListeners() {
        // 添加设备按钮
        document.getElementById('add-device-btn').addEventListener('click', () => {
            this.showAddDeviceModal();
        });
    },
    
    // 加载设备列表
    async loadDevices() {
        try {
            AttendanceApp.showLoading();
            
            const response = await AttendanceApp.api('/device/list');
            this.devices = response.data || [];
            
            this.renderDevices();
            AttendanceApp.hideLoading();
        } catch (error) {
            console.error('加载设备列表失败:', error);
            AttendanceApp.hideLoading();
            AttendanceApp.showNotification('加载设备列表失败', 'error');
        }
    },
    
    // 渲染设备列表
    renderDevices() {
        const container = document.getElementById('devices-grid');
        container.innerHTML = '';
        
        if (this.devices.length === 0) {
            container.innerHTML = `
                <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                    <i class="fas fa-desktop" style="font-size: 3rem; margin-bottom: 20px; opacity: 0.3;"></i>
                    <p>暂无设备，请添加设备</p>
                </div>
            `;
            return;
        }
        
        this.devices.forEach(device => {
            const card = this.createDeviceCard(device);
            container.appendChild(card);
        });
    },
    
    // 创建设备卡片
    createDeviceCard(device) {
        const card = document.createElement('div');
        card.className = 'device-card';
        card.dataset.deviceId = device.id;
        
        const statusClass = this.getStatusClass(device.status);
        const statusText = this.getStatusText(device.status);
        const lastSync = device.lastSyncTime ? AttendanceApp.formatDate(device.lastSyncTime, 'MM-DD HH:mm') : '从未同步';
        
        card.innerHTML = `
            <div class="device-header">
                <h4>${device.name}</h4>
                <p>${device.type || '考勤设备'}</p>
            </div>
            <div class="device-body">
                <div class="device-info">
                    <div class="device-info-item">
                        <label>设备编号:</label>
                        <span>${device.deviceId}</span>
                    </div>
                    <div class="device-info-item">
                        <label>IP地址:</label>
                        <span>${device.ipAddress}:${device.port}</span>
                    </div>
                    <div class="device-info-item">
                        <label>位置:</label>
                        <span>${device.location || '未设置'}</span>
                    </div>
                    <div class="device-info-item">
                        <label>状态:</label>
                        <span class="device-status ${statusClass}">${statusText}</span>
                    </div>
                    <div class="device-info-item">
                        <label>最后同步:</label>
                        <span>${lastSync}</span>
                    </div>
                </div>
                <div class="device-actions">
                    <button class="btn btn-primary" onclick="DeviceManager.testConnection('${device.id}')">
                        <i class="fas fa-wifi"></i>
                        测试连接
                    </button>
                    <button class="btn btn-warning" onclick="DeviceManager.restartDevice('${device.id}')">
                        <i class="fas fa-redo"></i>
                        重启
                    </button>
                    <button class="btn btn-secondary" onclick="DeviceManager.syncDevice('${device.id}')">
                        <i class="fas fa-sync"></i>
                        同步
                    </button>
                    <button class="btn btn-success" onclick="DeviceManager.editDevice('${device.id}')">
                        <i class="fas fa-edit"></i>
                        编辑
                    </button>
                    <button class="btn btn-danger" onclick="DeviceManager.deleteDevice('${device.id}')">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </div>
        `;
        
        return card;
    },
    
    // 获取状态样式类
    getStatusClass(status) {
        const classes = {
            'ONLINE': 'online',
            'OFFLINE': 'offline',
            'ERROR': 'error'
        };
        return classes[status] || 'offline';
    },
    
    // 获取状态文本
    getStatusText(status) {
        const texts = {
            'ONLINE': '在线',
            'OFFLINE': '离线',
            'ERROR': '错误'
        };
        return texts[status] || '未知';
    },
    
    // 显示添加设备模态框
    showAddDeviceModal() {
        const content = `
            <form id="add-device-form">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备名称 *</label>
                    <input type="text" name="name" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备编号 *</label>
                    <input type="text" name="deviceId" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备类型</label>
                    <select name="type" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="U160">中控U160</option>
                        <option value="FINGERPRINT">指纹考勤机</option>
                        <option value="FACE">人脸考勤机</option>
                        <option value="CARD">刷卡考勤机</option>
                    </select>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">IP地址 *</label>
                    <input type="text" name="ipAddress" required pattern="^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$" 
                           placeholder="192.168.1.100" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">端口号 *</label>
                    <input type="number" name="port" required min="1" max="65535" value="4370" 
                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备位置</label>
                    <input type="text" name="location" placeholder="如：办公楼一楼大厅" 
                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; gap: 8px;">
                        <input type="checkbox" name="enabled" checked>
                        <span>启用设备</span>
                    </label>
                </div>
            </form>
        `;
        
        AttendanceApp.showModal('添加设备', content, [
            {
                text: '取消',
                class: 'btn-secondary',
                onclick: () => AttendanceApp.hideModal()
            },
            {
                text: '添加',
                class: 'btn-primary',
                onclick: () => this.submitAddDevice()
            }
        ]);
    },
    
    // 提交添加设备
    async submitAddDevice() {
        const form = document.getElementById('add-device-form');
        const formData = new FormData(form);
        
        // 验证表单
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const deviceData = {
            name: formData.get('name'),
            deviceId: formData.get('deviceId'),
            type: formData.get('type'),
            ipAddress: formData.get('ipAddress'),
            port: parseInt(formData.get('port')),
            location: formData.get('location'),
            enabled: formData.has('enabled')
        };
        
        try {
            AttendanceApp.showLoading();
            
            const response = await AttendanceApp.api('/device/add', {
                method: 'POST',
                body: JSON.stringify(deviceData)
            });
            
            if (response.success) {
                AttendanceApp.hideModal();
                AttendanceApp.showNotification('设备添加成功', 'success');
                this.loadDevices(); // 重新加载设备列表
            } else {
                throw new Error(response.message || '添加失败');
            }
        } catch (error) {
            console.error('添加设备失败:', error);
            AttendanceApp.showNotification('添加设备失败: ' + error.message, 'error');
        } finally {
            AttendanceApp.hideLoading();
        }
    },
    
    // 测试设备连接
    async testConnection(deviceId) {
        const device = this.devices.find(d => d.id === deviceId);
        if (!device) return;
        
        try {
            const btn = event.target.closest('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 测试中...';
            btn.disabled = true;
            
            const response = await AttendanceApp.api(`/device/test/${deviceId}`, {
                method: 'POST'
            });
            
            if (response.success) {
                AttendanceApp.showNotification(`设备 ${device.name} 连接正常`, 'success');
                this.updateDeviceStatus(deviceId, 'ONLINE');
            } else {
                AttendanceApp.showNotification(`设备 ${device.name} 连接失败`, 'error');
                this.updateDeviceStatus(deviceId, 'OFFLINE');
            }
        } catch (error) {
            console.error('测试设备连接失败:', error);
            AttendanceApp.showNotification(`设备连接测试失败: ${error.message}`, 'error');
            this.updateDeviceStatus(deviceId, 'ERROR');
        } finally {
            const btn = event.target.closest('button');
            btn.innerHTML = '<i class="fas fa-wifi"></i> 测试连接';
            btn.disabled = false;
        }
    },
    
    // 重启设备
    async restartDevice(deviceId) {
        const device = this.devices.find(d => d.id === deviceId);
        if (!device) return;
        
        AttendanceApp.confirm(`确定要重启设备 "${device.name}" 吗？`, async () => {
            try {
                const btn = event.target.closest('button');
                const originalText = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 重启中...';
                btn.disabled = true;
                
                const response = await AttendanceApp.api(`/device/restart/${deviceId}`, {
                    method: 'POST'
                });
                
                if (response.success) {
                    AttendanceApp.showNotification(`设备 ${device.name} 重启成功`, 'success');
                } else {
                    throw new Error(response.message || '重启失败');
                }
            } catch (error) {
                console.error('重启设备失败:', error);
                AttendanceApp.showNotification(`设备重启失败: ${error.message}`, 'error');
            } finally {
                const btn = event.target.closest('button');
                btn.innerHTML = '<i class="fas fa-redo"></i> 重启';
                btn.disabled = false;
            }
        });
    },
    
    // 同步设备数据
    async syncDevice(deviceId) {
        const device = this.devices.find(d => d.id === deviceId);
        if (!device) return;
        
        try {
            const btn = event.target.closest('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 同步中...';
            btn.disabled = true;
            
            const response = await AttendanceApp.api(`/attendance/collect/${deviceId}`, {
                method: 'POST'
            });
            
            if (response.success) {
                const count = response.data?.recordCount || 0;
                AttendanceApp.showNotification(`设备 ${device.name} 同步成功，获取 ${count} 条记录`, 'success');
                this.updateDeviceLastSync(deviceId);
            } else {
                throw new Error(response.message || '同步失败');
            }
        } catch (error) {
            console.error('同步设备数据失败:', error);
            AttendanceApp.showNotification(`设备数据同步失败: ${error.message}`, 'error');
        } finally {
            const btn = event.target.closest('button');
            btn.innerHTML = '<i class="fas fa-sync"></i> 同步';
            btn.disabled = false;
        }
    },
    
    // 编辑设备
    editDevice(deviceId) {
        const device = this.devices.find(d => d.id === deviceId);
        if (!device) return;
        
        const content = `
            <form id="edit-device-form">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备名称 *</label>
                    <input type="text" name="name" value="${device.name}" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备编号 *</label>
                    <input type="text" name="deviceId" value="${device.deviceId}" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备类型</label>
                    <select name="type" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                        <option value="U160" ${device.type === 'U160' ? 'selected' : ''}>中控U160</option>
                        <option value="FINGERPRINT" ${device.type === 'FINGERPRINT' ? 'selected' : ''}>指纹考勤机</option>
                        <option value="FACE" ${device.type === 'FACE' ? 'selected' : ''}>人脸考勤机</option>
                        <option value="CARD" ${device.type === 'CARD' ? 'selected' : ''}>刷卡考勤机</option>
                    </select>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">IP地址 *</label>
                    <input type="text" name="ipAddress" value="${device.ipAddress}" required pattern="^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$" 
                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">端口号 *</label>
                    <input type="number" name="port" value="${device.port}" required min="1" max="65535" 
                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">设备位置</label>
                    <input type="text" name="location" value="${device.location || ''}" 
                           style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; gap: 8px;">
                        <input type="checkbox" name="enabled" ${device.enabled ? 'checked' : ''}>
                        <span>启用设备</span>
                    </label>
                </div>
            </form>
        `;
        
        AttendanceApp.showModal('编辑设备', content, [
            {
                text: '取消',
                class: 'btn-secondary',
                onclick: () => AttendanceApp.hideModal()
            },
            {
                text: '保存',
                class: 'btn-primary',
                onclick: () => this.submitEditDevice(deviceId)
            }
        ]);
    },
    
    // 提交编辑设备
    async submitEditDevice(deviceId) {
        const form = document.getElementById('edit-device-form');
        const formData = new FormData(form);
        
        // 验证表单
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const deviceData = {
            name: formData.get('name'),
            deviceId: formData.get('deviceId'),
            type: formData.get('type'),
            ipAddress: formData.get('ipAddress'),
            port: parseInt(formData.get('port')),
            location: formData.get('location'),
            enabled: formData.has('enabled')
        };
        
        try {
            AttendanceApp.showLoading();
            
            const response = await AttendanceApp.api(`/device/update/${deviceId}`, {
                method: 'POST',
                body: JSON.stringify(deviceData)
            });
            
            if (response.success) {
                AttendanceApp.hideModal();
                AttendanceApp.showNotification('设备更新成功', 'success');
                this.loadDevices(); // 重新加载设备列表
            } else {
                throw new Error(response.message || '更新失败');
            }
        } catch (error) {
            console.error('更新设备失败:', error);
            AttendanceApp.showNotification('更新设备失败: ' + error.message, 'error');
        } finally {
            AttendanceApp.hideLoading();
        }
    },
    
    // 删除设备
    async deleteDevice(deviceId) {
        const device = this.devices.find(d => d.id === deviceId);
        if (!device) return;
        
        AttendanceApp.confirm(`确定要删除设备 "${device.name}" 吗？此操作不可恢复。`, async () => {
            try {
                AttendanceApp.showLoading();
                
                const response = await AttendanceApp.api(`/device/delete/${deviceId}`, {
                    method: 'POST'
                });
                
                if (response.success) {
                    AttendanceApp.showNotification('设备删除成功', 'success');
                    this.loadDevices(); // 重新加载设备列表
                } else {
                    throw new Error(response.message || '删除失败');
                }
            } catch (error) {
                console.error('删除设备失败:', error);
                AttendanceApp.showNotification('删除设备失败: ' + error.message, 'error');
            } finally {
                AttendanceApp.hideLoading();
            }
        });
    },
    
    // 更新设备状态
    updateDeviceStatus(deviceId, status) {
        const device = this.devices.find(d => d.id === deviceId);
        if (device) {
            device.status = status;
            
            // 更新UI中的状态显示
            const card = document.querySelector(`[data-device-id="${deviceId}"]`);
            if (card) {
                const statusElement = card.querySelector('.device-status');
                statusElement.className = `device-status ${this.getStatusClass(status)}`;
                statusElement.textContent = this.getStatusText(status);
            }
        }
    },
    
    // 更新设备最后同步时间
    updateDeviceLastSync(deviceId) {
        const device = this.devices.find(d => d.id === deviceId);
        if (device) {
            device.lastSyncTime = new Date().toISOString();
            
            // 更新UI中的同步时间显示
            const card = document.querySelector(`[data-device-id="${deviceId}"]`);
            if (card) {
                const syncElement = card.querySelector('.device-info-item:last-child span');
                syncElement.textContent = AttendanceApp.formatDate(device.lastSyncTime, 'MM-DD HH:mm');
            }
        }
    },
    
    // 开始设备监控
    startDeviceMonitoring() {
        // 每2分钟检查一次设备状态
        setInterval(() => {
            this.checkAllDevicesStatus();
        }, 120000);
    },
    
    // 检查所有设备状态
    async checkAllDevicesStatus() {
        if (AttendanceApp.currentPage !== 'devices') {
            return; // 只在设备管理页面时检查
        }
        
        for (const device of this.devices) {
            try {
                const response = await AttendanceApp.api(`/device/ping/${device.id}`, {
                    method: 'POST'
                });
                
                const newStatus = response.success ? 'ONLINE' : 'OFFLINE';
                if (device.status !== newStatus) {
                    this.updateDeviceStatus(device.id, newStatus);
                }
            } catch (error) {
                if (device.status !== 'ERROR') {
                    this.updateDeviceStatus(device.id, 'ERROR');
                }
            }
        }
    }
};

